<?php

namespace App\Api\Controller;

use App\Bundle\Goods\GoodsService;
use App\Bundle\Goods\GroupService;
use Core\Application\Controller;
use Core\Support\Arr;
use Core\Support\Validate;

class GoodsController extends Controller
{
    protected $goodsService;
    protected $groupService;

    public function __construct()
    {
        parent::__construct();
        $this->goodsService = GoodsService::getInstance();
        $this->groupService = GroupService::getInstance();
    }

    //  添加商品
    #[Validate('name', '请填写商品名称')]
    #[Validate('price', '请填写商品价格')]
    public function add()
    {
        $input = $this->getInputJson();

        $shop = $this->goodsService->add($input);
        return $this->success($shop);
    }

    // 商品列表
    #[Validate('shopId', '缺少店铺参数')]
    public function list()
    {
        $criteria = $this->getInputAll();

        $list = $this->goodsService->newQuery()
            ->whereShopId(Arr::get($criteria, 'shopId'))
            ->whereStateEnabled()
            ->orderBy('price')
            ->list();

        return $this->success($list);
    }

    // 商品分组列表
    #[Validate('shopId', '缺少店铺参数')]
    #[Validate('groupId', '缺少分组参数')]
    public function listByGroup()
    {
        $criteria = $this->getInputAll();

        // 获取分组
        $list = $this->goodsService->listByGroup(
            Arr::get($criteria, 'shopId'),
            Arr::get($criteria, 'groupId'),
            ['state' => 1]
        );

        return $this->success($list);
    }

    // 更新商品信息
    public function update($goodsId)
    {
        $input = $this->getInputJson();

        $this->goodsService->update($goodsId, $input);
        return $this->success();
    }

    // 获取商品信息
    public function detail($goodsId)
    {
        $detail = $this->goodsService->detail($goodsId);
        return $this->success($detail);
    }

    // 删除商品
    public function delete($goodsId)
    {
        $this->goodsService->delete($goodsId);
        return $this->success();
    }

    // 获取商品分组列表
    // #[Validate('shopId', '缺少店铺参数')]
    // public function groupList()
    // {
    //     $criteria = $this->getInputAll();

    //     $all = $this->groupService->newQuery()
    //         ->whereShopId(Arr::get($criteria, 'shopId'))
    //         ->whereStateEnabled()
    //         ->orderBy('position')
    //         ->all();

    //     return $this->success($all);
    // }

    #[Validate('shopId', '缺少店铺参数')]
    public function groupList()
    {
        $criteria = $this->getInputAll();

        $all = $this->groupService->newQuery()
            ->whereShopId(Arr::get($criteria, 'shopId'))
            ->whereStateEnabled()
            ->orderBy('top', 'desc')
            ->all();

        return $this->success($all);
    }

    public function groupAdd()
    {
        # code...
    }

    public function groupUpdate()
    {
        # code...
    }

    public function groupDelete()
    {
        # code...
    }
}
